package sf_ctx

import (
	"engine/consts"
	"engine/model"
	"lib/log"
	sferrors "lib/sf-errors"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

type CmsCtxValue struct {
	User        *model.SysUserDetail
	Permissions []*model.CorePermission
}

func GetCmsCtxValue(ctx *gin.Context) (*CmsCtxValue, error) {
	ctxValue, exists := ctx.Get("value")
	if !exists {
		return nil, sferrors.Code(sferrors.InvalidUserError)
	}
	cmsCtxValue, ok := ctxValue.(*CmsCtxValue)
	if !ok {
		return nil, sferrors.Code(sferrors.InvalidUserError)
	}
	return cmsCtxValue, nil
}

const AgencyContextKey = "agency-ctx-key"

func GetModule(ctx *gin.Context) consts.SystemModule {
	module, ok := ctx.Value("module").(consts.SystemModule)
	if !ok {
		return consts.ModuleNone
	}
	return module
}

func GetParamId(ctx *gin.Context) (uint64, error) {
	idStr := ctx.Param("id")
	if strings.EqualFold(idStr, "") {
		return 0, sferrors.Code(sferrors.InvalidParameter)
	}
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		return 0, sferrors.New(err).SetCode(sferrors.InvalidParameter)
	}

	if id == 0 {
		return 0, sferrors.NewString("获取id失败").SetCode(sferrors.InvalidParameter)
	}

	return id, nil
}
